package com.demo.dao.mapper;

import static org.apache.ibatis.jdbc.SqlBuilder.*;
import static org.apache.ibatis.jdbc.SqlBuilder.DELETE_FROM;
import static org.apache.ibatis.jdbc.SqlBuilder.SET;
import static org.apache.ibatis.jdbc.SqlBuilder.SQL;
import static org.apache.ibatis.jdbc.SqlBuilder.UPDATE;
import static org.apache.ibatis.jdbc.SqlBuilder.WHERE;

import java.util.Map;

import com.demo.model.User;

public class UserMapper {

	// BEGIN();
	// INSERT_INTO("user");
	// VALUES("username", "#{username}");
	// VALUES("password", "#{password}");
	// VALUES("nickname", "#{nickname}");
	// return SQL();
	public String insert(User user) {
		return "insert into user (username, password, nickname) values (#{username},#{password},#{nickname})";
	}
	
	public String selectByUsernameAndPassward(Map<String, Object> parameter) {
//		String username = (String) parameter.get("username");
//		String password = (String) parameter.get("password");
		return "select * from user where username=#{username} and password=#{password}";
	}
	
	private void where(String username) {
		if (username != null && username.length() > 0) {
			WHERE("username=#{username}");
		}
	}

	public String select(Map<String, Object> parameter) {
		String username = (String) parameter.get("username");
		int pageNo = (int) parameter.get("pageNo");
		int pageSize = (int) parameter.get("pageSize");
		
		BEGIN();
		SELECT("*");
		FROM("user");
		where(username);
		ORDER_BY("id desc");
		return SQL() + " limit " + pageNo * pageSize + ", " + pageSize;
	}
	
	public String count(String username) {
		BEGIN();
		SELECT("count(*)");
		FROM("user");
		where(username);
		return SQL();
	}

	public String selectOne(Integer id) {
		return "select * from user where id=#{id}";
	}

	public String update(User user) {
		BEGIN();
		UPDATE("user");
		if (user.getNickname() != null && user.getNickname().length() > 0) {
			SET("nickname=#{nickname}");
		}
		if (user.getPassword() != null && user.getPassword().length() > 0) {
			SET("password=#{password}");
		}
		WHERE("id=#{id}");
		String sql = SQL();
		System.out.println(sql);
		return sql;
	}

	public String delete(long id) {
		BEGIN();
		DELETE_FROM("user");
		WHERE("id=#{id}");
		return SQL();
	}
}
